package com.tisson.dict.pingserver.component;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

@Component
public class RateLimiter {
    private static final String RATE_LIMIT_FILE = "rate_limit.txt";

    public boolean allowRequest() {
        try (RandomAccessFile file = new RandomAccessFile(RATE_LIMIT_FILE, "rw");
             FileChannel channel = file.getChannel();
             FileLock lock = channel.lock()) {

            long currentTimeSeconds = System.currentTimeMillis() / 1000;
            long lastTimestamp = 0;
            int count = 0;

            if (file.length() > 0) {
                String[] parts = file.readLine().split(",");
                lastTimestamp = Long.parseLong(parts[0]);
                count = Integer.parseInt(parts[1]);
            }

            if (currentTimeSeconds > lastTimestamp) {
                lastTimestamp = currentTimeSeconds;
                count = 0;
            }

            if (count < 2) {
                count++;
                file.setLength(0);
                file.writeBytes(lastTimestamp + "," + count);
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
    }
}
